<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use Exception;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class UserController extends Controller
{
    /**
     * 用户登录
     */
    public function login(Request $request)
    {
        // 验证请求参数 - 前端使用username参数
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
        ]);

        // 使用name列查找用户（前端使用username参数）
        $user = User::where('name', $request->username)->first();

        // 验证用户和密码
        if (!$user || !Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'error' => ['用户名或密码错误']
            ]);
        }

        // 确保删除所有旧token，防止多个token同时有效
        $user->tokens()->delete();
        
        // 生成新token
        $token = $user->createToken('auth_token', ['*'])->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'username' => $user->name, // 返回name作为username
                'email' => $user->email,
                'is_admin' => $user->is_admin // 返回管理员状态
            ],
            'message' => '登录成功'
        ]);
    }

    /**
     * 用户注册
     */
    public function register(Request $request)
    {
        try {
            // 验证请求数据
            $validator = validator()->make($request->all(), [
                'username' => 'required|min:3|max:20|alpha_dash|unique:users,name',
                'email' => 'required|email|unique:users,email',
                'password' => 'required|min:6',
                'phone' => 'nullable|regex:/^1[3-9]\d{9}$/'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'error' => '验证失败',
                    'errors' => $validator->errors()
                ], 400);
            }

            // 记录请求数据用于调试
            Log::info('Registration attempt with data:', $request->all());

            // 创建新用户
            $user = User::create([
                'name' => $request->username,  // 前端使用username参数，后端存储到name字段
                'email' => $request->email,
                'password' => Hash::make($request->password),  // 密码哈希处理
                'phone' => $request->phone  // 可选的手机号字段
            ]);

            // 返回成功响应
            return response()->json([
                'message' => '注册成功',
                'user' => [
                    'id' => $user->id,
                    'username' => $user->name,
                    'email' => $user->email,
                    'phone' => $user->phone
                ]
            ], 201);
        } catch (Exception $e) {
            // 记录错误详情
            Log::error('Registration error:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            // 返回友好的错误信息
            return response()->json([
                'error' => '注册失败',
                'message' => '系统内部错误，请稍后重试',
                'debug' => $e->getMessage() // 生产环境中应该移除这一行
            ], 500);
        }
    }

    /**
     * 获取当前用户信息
     */
    public function me(Request $request)
    {
        $user = $request->user();
        
        return response()->json([
            'user' => [
                'id' => $user->id,
                'username' => $user->name, // 返回name作为username
                'email' => $user->email,
                'phone' => $user->phone ?? '',
                'is_admin' => $user->is_admin // 返回管理员状态
            ]
        ]);
    }

    /**
     * 手机号直接登录
     */
    public function loginWithSms(Request $request)
    {
        $request->validate([
            'phone' => 'required|regex:/^1[3-9]\d{9}$/'
        ]);

        // 查找用户
        $user = User::where('phone', $request->phone)->first();
        
        if (!$user) {
            throw ValidationException::withMessages([
                'message' => ['该手机号未注册']
            ]);
        }

        // 删除旧token
        $user->tokens()->delete();
        
        // 生成新token
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'username' => $user->name, // 返回name作为username
                'email' => $user->email
            ]
        ]);
    }

    /**
     * 重置密码
     */
    public function resetPassword(Request $request)
    {
        $request->validate([
            'username' => 'required',
            'email' => 'required|email',
            'newPassword' => 'required|min:6'
        ]);

        // 查找用户，使用name列
        $user = User::where('name', $request->username)
                   ->where('email', $request->email)
                   ->first();

        if (!$user) {
            throw ValidationException::withMessages([
                'message' => ['用户名和邮箱不匹配']
            ]);
        }

        // 更新密码
        $user->password = Hash::make($request->newPassword);
        $user->save();

        // 删除所有token
        $user->tokens()->delete();

        return response()->json([
            'message' => '密码重置成功'
        ]);
    }
    
    /**
     * 用户登出
     */
    public function logout(Request $request)
    {
        $user = $request->user();
        if ($user) {
            // 删除用户的所有token
            $user->tokens()->delete();
        }
        
        return response()->json([
            'message' => '登出成功'
        ]);
    }
    
    /**
     * 注销账号
     */
    public function deleteAccount(Request $request)
    {
        try {
            // 获取当前用户
            $user = $request->user();
            
            // 记录注销日志
            Log::info('用户注销账号:', ['user_id' => $user->id, 'username' => $user->name]);
            
            // 删除用户的所有令牌
            $user->tokens()->delete();
            
            // 删除用户相关数据（可以根据业务需求扩展）
            // 例如删除用户的订单、评论等
            
            // 删除用户账号
            $user->delete();
            
            return response()->json(['message' => '账号注销成功']);
        } catch (Exception $e) {
            Log::error('注销账号失败:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return response()->json(['error' => '注销账号失败'], 500);
        }
    }
    
    /**
     * 获取所有用户 - 管理员功能
     */
    public function index(Request $request)
    {
        try {
            // 确保从数据库获取所有用户
            $users = User::orderBy('created_at', 'desc')->get();
            
            // 转换用户数据格式，适配前端需求
            $formattedUsers = $users->map(function ($user) {
                return [
                    'id' => $user->id,
                    'username' => $user->name,
                    'email' => $user->email,
                    'phone' => $user->phone ?? '',
                    'is_admin' => (bool) $user->is_admin,
                    'created_at' => $user->created_at->toDateTimeString()
                ];
            });
            
            // 直接返回用户数组，前端api拦截器会处理响应格式
            return response()->json($formattedUsers);
        } catch (Exception $e) {
            Log::error('获取用户列表失败:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return response()->json(['error' => '获取用户列表失败'], 500);
        }
    }
    
    /**
     * 测试方法：直接返回所有用户，不进行任何处理
     * 用于调试和验证数据库连接
     */
    public function getAllUsersRaw(Request $request)
    {
        // 检查权限
        if (!$request->user() || !$request->user()->is_admin) {
            return response()->json(['error' => '权限不足'], 403);
        }
        
        // 直接从数据库获取所有用户
        $users = User::orderBy('created_at', 'desc')->get();
        
        // 返回原始用户数据，包含数据库中的所有字段
        return response()->json([
            'users' => $users,
            'count' => $users->count(),
            'message' => '直接从数据库获取的用户列表'
        ]);
    }
    
    /**
     * 获取单个用户详情 - 管理员功能
     */
    public function show(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);
            
            return response()->json([
                'id' => $user->id,
                'username' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone ?? '',
                'is_admin' => (bool) $user->is_admin,
                'created_at' => $user->created_at->toDateTimeString()
            ]);
        } catch (Exception $e) {
            Log::error('获取用户详情失败:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'user_id' => $id
            ]);
            return response()->json(['error' => '用户不存在'], 404);
        }
    }
    
    /**
     * 创建新用户 - 管理员功能
     */
    public function store(Request $request)
    {
        try {
            // 验证请求数据
            $request->validate([
                'username' => 'required|min:3|max:20|alpha_dash|unique:users,name',
                'email' => 'required|email|unique:users,email',
                'password' => 'required|min:6',
                'is_admin' => 'boolean'
            ]);
            
            Log::info('管理员创建新用户:', $request->all());
            
            // 创建新用户
            $user = User::create([
                'name' => $request->username,
                'email' => $request->email,
                'password' => Hash::make($request->password),
                'is_admin' => $request->is_admin ?? false
            ]);
            
            return response()->json([
                'message' => '用户创建成功',
                'user' => [
                    'id' => $user->id,
                    'username' => $user->name,
                    'email' => $user->email,
                    'is_admin' => (bool) $user->is_admin
                ]
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'error' => '验证失败',
                'errors' => $e->errors()
            ], 400);
        } catch (Exception $e) {
            Log::error('创建用户失败:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return response()->json(['error' => '创建用户失败'], 500);
        }
    }
    
    /**
     * 更新用户信息 - 管理员功能
     */
    public function update(Request $request, $id)
    {
        try {
            $user = User::findOrFail($id);
            
            // 如果是更新自己的管理员状态，阻止操作
            if ($request->user()->id == $id && isset($request->is_admin)) {
                return response()->json(['error' => '不能修改自己的管理员状态'], 403);
            }
            
            // 准备验证规则
            // 只验证实际提交的字段，这样可以单独更新is_admin状态
            $rules = [];
            
            // 如果提交了username，则验证
            if ($request->has('username')) {
                $rules['username'] = 'required|min:3|max:20|alpha_dash|unique:users,name,' . $id;
            }
            
            // 如果提交了email，则验证
            if ($request->has('email')) {
                $rules['email'] = 'required|email|unique:users,email,' . $id;
            }
            
            // 如果提交了is_admin，则验证
            if ($request->has('is_admin')) {
                $rules['is_admin'] = 'boolean';
            }
            
            // 如果提供了密码，则验证
            if ($request->has('password')) {
                $rules['password'] = 'min:6';
            }
            
            // 验证请求数据
            $request->validate($rules);
            
            // 准备更新数据
            $updateData = [];
            
            // 只添加请求中实际提供的字段
            if ($request->has('username')) {
                $updateData['name'] = $request->username;
            }
            
            if ($request->has('email')) {
                $updateData['email'] = $request->email;
            }
            
            // 如果提供了管理员状态且不是修改自己，则更新
            if (isset($request->is_admin) && $request->user()->id != $id) {
                $updateData['is_admin'] = $request->is_admin;
            }
            
            // 如果提供了密码，则更新
            if ($request->has('password')) {
                $updateData['password'] = Hash::make($request->password);
                // 更新密码后删除用户的所有token
                $user->tokens()->delete();
            }
            
            // 更新用户
            $user->update($updateData);
            
            return response()->json([
                'message' => '用户更新成功',
                'user' => [
                    'id' => $user->id,
                    'username' => $user->name,
                    'email' => $user->email,
                    'is_admin' => (bool) $user->is_admin
                ]
            ]);
        } catch (ValidationException $e) {
            return response()->json([
                'error' => '验证失败',
                'errors' => $e->errors()
            ], 400);
        } catch (Exception $e) {
            Log::error('更新用户失败:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'user_id' => $id
            ]);
            return response()->json(['error' => '更新用户失败'], 500);
        }
    }
    
    /**
     * 删除用户 - 管理员功能
     */
    public function destroy(Request $request, $id)
    {
        try {
            // 不允许删除自己
            if ($request->user()->id == $id) {
                return response()->json(['error' => '不能删除自己'], 403);
            }
            
            // 查找用户
            $user = User::findOrFail($id);
            
            // 删除用户的所有token
            $user->tokens()->delete();
            
            // 删除用户
            $user->delete();
            
            return response()->json(['message' => '用户删除成功']);
        } catch (Exception $e) {
            Log::error('删除用户失败:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'user_id' => $id
            ]);
            return response()->json(['error' => '删除用户失败'], 500);
        }
    }
}